package com.gs.synedocket.fragment.docket;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.gs.synedocket.R;
import com.gs.synedocket.activity.LocationActivity;
import com.gs.synedocket.apiresult.ApiResultData;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.constant.EventCode;
import com.gs.synedocket.control.DocketLineView;
import com.gs.synedocket.control.DocketView;
import com.gs.synedocket.db.bean.Event;
import com.gs.synedocket.db.dao.LogUtil;
import com.gs.synedocket.db.dto.DocketDto;
import com.gs.synedocket.db.dto.DocketSiteDto;
import com.gs.synedocket.db.dto.ShortDto;
import com.gs.synedocket.dialog.LoadingDialogUtils;
import com.gs.synedocket.dialog.ToastDialogUtils;
import com.gs.synedocket.fragment.base.BaseFragment;
import com.gs.synedocket.presenter.DocketPresenter;
import com.gs.synedocket.util.DateUtil;
import com.gs.synedocket.util.DocketUtil;
import com.gs.synedocket.util.PermissionUtil;
import com.gs.synedocket.util.ToastUtil;
import com.gs.synedocket.view.IDocketView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class DocketFragment extends BaseFragment<IDocketView, DocketPresenter> implements IDocketView {

    private List<Fragment> fragmentList;
    private List<String> fragmentTag;
    private Fragment mFragment;
    private int fragmentIndex;
    private DocketView viewDocketNo, viewContactPerson, viewTelNo, viewVehicleNo,
            viewPlant, viewSlump, viewLoadQty, viewCumulativeQty, viewOrderQty, viewDate,
            viewCementBrand, viewMaxAgg, viewAdmixtures, viewBuyerCode, viewSiteCode,
            viewSpecialTeam, viewCharge1, viewCharge2, viewLastTel;
    private DocketLineView viewBuyerName, viewSiteLoc, viewConcreteMix, viewBatchTime;
    private String phone;
    private SmartRefreshLayout smartRefreshLayout;
    private ScrollView scrollView;
    private LinearLayout llOn;
    private String location;
    private boolean isTruckChange;
    private long lastSyncTime;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_docket;
    }

    @Override
    protected DocketPresenter createPresenter() {
        return new DocketPresenter();
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        scrollView = fd(R.id.scrollView);
        llOn = fd(R.id.ll_on);
        fragmentList = new ArrayList<>();
        fragmentTag = new ArrayList<>();
        DocketQcCheckFragment docketQcCheckFragment = new DocketQcCheckFragment();
        DocketOkFragment docketOkFragment = new DocketOkFragment();
        DocketAdditionalFragment docketAdditionalFragment = new DocketAdditionalFragment();
        fragmentList.add(docketQcCheckFragment);
        fragmentList.add(docketOkFragment);
        fragmentList.add(docketAdditionalFragment);
        fragmentTag.add(DocketQcCheckFragment.class.getSimpleName());
        fragmentTag.add(DocketOkFragment.class.getSimpleName());
        fragmentTag.add(DocketAdditionalFragment.class.getSimpleName());
        smartRefreshLayout = fd(R.id.smartRefreshLayout);
        smartRefreshLayout.setEnableLoadMore(false);
        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            initData();
            downloadData();
        });
        viewDocketNo = fd(R.id.view_docket_no);
        viewBuyerName = fd(R.id.view_buyer_name);
        viewSiteLoc = fd(R.id.view_site_loc);
        viewContactPerson = fd(R.id.view_contact_person);
        viewTelNo = fd(R.id.view_tel_no);
        viewVehicleNo = fd(R.id.view_vehicle_no);
        viewPlant = fd(R.id.view_plant);
        viewConcreteMix = fd(R.id.view_concrete_mix);
        viewSlump = fd(R.id.view_slump);
        viewLoadQty = fd(R.id.view_load_qty);
        viewCumulativeQty = fd(R.id.view_cumulative_qty);
        viewOrderQty = fd(R.id.view_order_qty);
        viewDate = fd(R.id.view_date);
        viewBatchTime = fd(R.id.view_batch_time);
        viewCementBrand = fd(R.id.view_cement_brand);
        viewMaxAgg = fd(R.id.view_max_agg);
        viewAdmixtures = fd(R.id.view_admixtures);
        viewBuyerCode = fd(R.id.view_buyer_code);
        viewSiteCode = fd(R.id.view_site_code);
        viewSpecialTeam = fd(R.id.view_special_term);
        viewCharge1 = fd(R.id.view_charge1);
        viewCharge2 = fd(R.id.view_charge2);
        viewLastTel = fd(R.id.view_last_tel);
        viewSiteLoc.setOnClickListener(v -> {
            if (TextUtils.isEmpty(location)) {
                ToastUtil.showToast(R.string.no_gps);
                return;
            }
            Intent intent = new Intent(context, LocationActivity.class);
            intent.putExtra(AllConstants.LOCATION, location);
            startActivity(intent);
            LogUtil.getInstance().insertOrReplaceData("查看送貨單" + DocketUtil.getInstance().getDocketNo() + "地盤位置");
        });
        viewTelNo.setOnClickListener(v -> {
            if (TextUtils.isEmpty(phone)) {
                ToastUtil.showToast(R.string.no_tel_no);
                return;
            }
            if (PermissionUtil.addPermission(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, AllConstants.CALL_PHONE)) {
                Intent intent = new Intent(Intent.ACTION_CALL);
                Uri data = Uri.parse("tel:" + phone);
                intent.setData(data);
                startActivity(intent);
                LogUtil.getInstance().insertOrReplaceData("撥打送貨單" + DocketUtil.getInstance().getDocketNo() + "裡的電話號碼" + phone);
            }
        });
    }

    private void downloadData() {
        if (DocketUtil.getInstance().getDocketId().isEmpty()
//                || !SPUtil.getInstance().getBoolean(AllConstants.IS_DOWNLOAD, true))
                && System.currentTimeMillis() - lastSyncTime > 3000L) {
            EventBus.getDefault().post(new Event(EventCode.EVENT_REFRESH_DOWNLOAD));
            lastSyncTime = System.currentTimeMillis();
        }
    }

    @Override
    protected void initData() {
        showLoading();
        mPresenter.getData(DocketUtil.getInstance().getDocketId());
    }

    @Override
    public void onGetDataSuccess(ApiResultData<DocketDto> apiResultData) {
        smartRefreshLayout.finishRefresh();
        if (apiResultData.getStatus() != 2000) {
            if (!isTruckChange) {
                ToastDialogUtils.getInstance().showInfoMessage(context, apiResultData.getMessage());
            }
            isTruckChange = false;
            return;
        }
        DocketDto data = apiResultData.getData();
        if (data == null || data.getId() == null) {
            if (!isTruckChange) {
                ToastDialogUtils.getInstance().showInfoMessage(context, R.string.empty_docket);
            }
            refreshView();
            isTruckChange = false;
            return;
        }
        String docketNo = data.getDocketNo() == null ? "" : data.getDocketNo();
        LogUtil.getInstance().insertOrReplaceData("獲取送貨單" + docketNo + "信息");
        viewDocketNo.setContent(docketNo);
        viewContactPerson.setContent(data.getContactPerson() == null ? "" : data.getContactPerson());
        phone = data.getContactTel() == null ? "" : data.getContactTel();
        viewTelNo.setContent(phone);
        ShortDto customer = data.getCustomer();
        if (customer != null) {
            viewBuyerName.setContent(customer.getName() == null ? "" : customer.getName());
            viewBuyerCode.setContent(customer.getCode());
        } else {
            viewBuyerName.setContent("");
            viewBuyerCode.setContent("");
        }
        DocketSiteDto site = data.getSite();
        if (site != null) {
            String siteName = site.getName();
            String extraAddress = data.getExtraAddress();
            String name = (siteName == null ? "" : siteName) + (extraAddress == null ? "" : " " + extraAddress);
            viewSiteLoc.setContent(name);
            DocketUtil.getInstance().setDocketSite(name);
            viewSiteCode.setContent(site.getCode() == null ? "" : site.getCode());
            location = site.getGps();
        } else {
            viewSiteLoc.setContent("");
            viewSiteCode.setContent("");
        }
        ShortDto product = data.getProduct();
        if (product != null) {
            viewConcreteMix.setContent(product.getName() == null ? "" : product.getName());
        } else {
            viewConcreteMix.setContent("");
        }
        ShortDto cement = data.getCement();
        if (cement != null) {
            viewCementBrand.setContent(cement.getName() == null ? "" : cement.getName());
        } else {
            viewCementBrand.setContent("");
        }
        List<ShortDto> admixtures = data.getAdmixtures();
        if (admixtures != null && !admixtures.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (ShortDto bean : admixtures) {
                sb.append(",").append(bean.getName() == null ? "" : bean.getName());
            }
            viewAdmixtures.setContent(sb.substring(1));
        } else {
            viewAdmixtures.setContent("");
        }
        ShortDto plant = data.getPlant();
        if (plant != null) {
            viewPlant.setContent(plant.getName() == null ? "" : plant.getName());
        } else {
            viewPlant.setContent("");
        }
        viewMaxAgg.setContent(data.getNominalMaxAgg() == null ? "" : data.getNominalMaxAgg() + "MM");
        viewSlump.setContent(data.getSlump() == null ? "" : data.getSlump() + "");
        viewVehicleNo.setContent(data.getTruckNo() == null ? "" : data.getTruckNo());
        viewLoadQty.setContent(data.getLoadQty() == null ? "" : String.valueOf(data.getLoadQty()));
        viewCumulativeQty.setContent(data.getCumQty() == null ? "" : String.valueOf(data.getCumQty()));
        viewOrderQty.setContent(data.getOrderQty() == null ? "" : String.valueOf(data.getOrderQty()));
        viewDate.setContent(DateUtil.DateTimeToStr(data.getDocketAt()));
        viewBatchTime.setContent(DateUtil.DateTimeToStr(data.getBatchTime(), "HH:mm"));
        viewSpecialTeam.setContent(data.getSpecialTerm() == null ? "" : data.getSpecialTerm());
        viewCharge1.setContent(data.getAdditionalCharge1() == null ? "" : data.getAdditionalCharge1());
        viewCharge2.setContent(data.getAdditionalCharge2() == null ? "" : data.getAdditionalCharge2());
        viewLastTel.setContent(data.getPreTruckNo() == null ? "" : data.getPreTruckNo());
        DocketUtil.getInstance().setDocketId(data.getId());
        DocketUtil.getInstance().setTruckState(data.getTruckState());
        DocketUtil.getInstance().setDriverState(data.getState());
        DocketUtil.getInstance().setQcState(data.getQcState());
        DocketUtil.getInstance().setTruckNo(data.getTruckNo());
        DocketUtil.getInstance().setDocketNo(docketNo);
        DocketUtil.getInstance().setLoadQty(data.getLoadQty() == null ? 0 : data.getLoadQty());
        DocketUtil.getInstance().setArriveSiteAt(data.getArriveSiteAt());
        DocketUtil.getInstance().setArriveSiteGps(data.getArriveSiteGps());
        DocketUtil.getInstance().setStartDisAt(data.getStartDisAt());
        DocketUtil.getInstance().setStartDisGps(data.getStartDisGps());
        DocketUtil.getInstance().setEndDisAt(data.getEndDisAt());
        DocketUtil.getInstance().setEndDisGps(data.getEndDisGps());
        DocketUtil.getInstance().setLeaveSiteAt(data.getLeaveSiteAt());
        DocketUtil.getInstance().setLeaveSiteGps(data.getLeaveSiteGps());
        DocketUtil.getInstance().setQrCodeAuth(data.getAuthorityQRCode() == null ? "" : data.getAuthorityQRCode());
        DocketUtil.getInstance().setQrCodeCus(data.getCustQRCode() == null ? "" : data.getCustQRCode());
        DocketUtil.getInstance().setQrCodeKWah(data.getkWahQRCode() == null ? "" : data.getkWahQRCode());
        DocketUtil.getInstance().setAccRep(data.getAccRep());
        DocketUtil.getInstance().setPhotos(data.getDocketPhotos());
        DocketUtil.getInstance().setDriverRemark(data.getDriverRemark());
        DocketUtil.getInstance().setAdditional(data.getAdditional());
        DocketUtil.getInstance().setUpload(data.getUpload() == null ? 1 : data.getUpload());
        EventBus.getDefault().post(new Event(EventCode.EVENT_DONE_ON_HAND, isTruckChange));
        hideFragment(mFragment);
        isTruckChange = false;
    }

    private void refreshView() {
        DocketUtil.getInstance().refresh();
        location = "";
        viewDocketNo.setContent("");
        viewBuyerName.setContent("");
        viewContactPerson.setContent("");
        phone = "";
        viewTelNo.setContent("");
        viewBuyerCode.setContent("");
        viewSiteLoc.setContent("");
        viewSiteCode.setContent("");
        viewConcreteMix.setContent("");
        viewSlump.setContent("");
        viewCementBrand.setContent("");
        viewMaxAgg.setContent("");
        viewAdmixtures.setContent("");
        viewPlant.setContent("");
        viewVehicleNo.setContent("");
        viewLoadQty.setContent("");
        viewCumulativeQty.setContent("");
        viewOrderQty.setContent("");
        viewDate.setContent("");
        viewBatchTime.setContent("");
        viewSpecialTeam.setContent("");
        viewCharge1.setContent("");
        viewCharge2.setContent("");
        viewLastTel.setContent("");
        EventBus.getDefault().post(new Event(EventCode.EVENT_DONE_ON_HAND, isTruckChange));
    }

    @Override
    public void onGetDataFail(Exception e) {
        refreshView();
        if (!isTruckChange) {
            smartRefreshLayout.finishRefresh();
            ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
        }
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(context);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    private Fragment getFragment() {
        return fragmentList.get(fragmentIndex);
    }

    private String getFragmentTag() {
        return fragmentTag.get(fragmentIndex);
    }

    private void showFragment(Fragment fromFragment, Fragment toFragment, String tag) {
        if (fromFragment != toFragment) {
            mFragment = toFragment;
            FragmentManager fm = getChildFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            if (fromFragment != null) {
                transaction.hide(fromFragment);
            }
            if (toFragment.isAdded()) {
                transaction.show(toFragment);
            } else {
                transaction.add(R.id.fl_content, toFragment, tag);
            }
            transaction.commit();
        }
    }

    private void hideFragment(Fragment fromFragment) {
        FragmentManager fm = getChildFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        if (fromFragment != null) {
            transaction.hide(fromFragment);
            transaction.commit();
            mFragment = null;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event) {
        int what = event.getWhat();
        switch (what) {
            case EventCode.EVENT_VOID:
                ToastUtil.showToast(R.string.docket_void);
                mPresenter.getData("");
                break;
            case EventCode.EVENT_CHANGE_TRUCK:
                ToastUtil.showToast(R.string.docket_truck_change);
                mPresenter.getData("");
                break;
            case EventCode.EVENT_DOWNLOAD_SUCCESS:
                mPresenter.getData("");
                break;
            case EventCode.EVENT_RETURN_DOCKET:
            case EventCode.EVENT_ON_HAND:
                initData();
                scrollTo(0);
                break;
            case EventCode.EVENT_ARRIVE_PLANT:
                initData();
                scrollTo(0);
                downloadData();
                break;
            case EventCode.EVENT_TRUCK:
                isTruckChange = true;
                DocketUtil.getInstance().setDocketId("");
                mPresenter.getData("");
                scrollTo(0);
                break;
            case EventCode.EVENT_ARRIVE_SITE:
                fragmentIndex = 0;
                showFragment(mFragment, getFragment(), getFragmentTag());
                scrollTo(llOn.getHeight() + 100);
                break;
            case EventCode.EVENT_SCROLLVIEW:
                scrollTo(llOn.getHeight() + 100);
                break;
            case EventCode.EVENT_DONE_QC_CHECK:
            case EventCode.EVENT_DONE_COMPLETE:
            case EventCode.EVENT_DONE_REVERT_SIGN:
                hideFragment(mFragment);
                break;
            case EventCode.EVENT_OK:
                fragmentIndex = 1;
                showFragment(mFragment, getFragment(), getFragmentTag());
                scrollTo(llOn.getHeight() + 50);
                break;
            case EventCode.EVENT_ADDITIONAL:
                fragmentIndex = 2;
                showFragment(mFragment, getFragment(), getFragmentTag());
                scrollTo(llOn.getHeight() + 50);
                break;
            case EventCode.EVENT_HIDE_SIGN:
                if (mFragment != null) {
                    hideFragment(mFragment);
                }
                break;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            hideFragment(mFragment);
            scrollTo(0);
        }
    }

    private void scrollTo(int y) {
        scrollView.postDelayed(() -> scrollView.scrollTo(0, y), 100);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getFragment().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        getFragment().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
